package com.guanyua.eims.service.impl;

import com.guanyua.eims.common.util.JsonUtil;
import com.guanyua.eims.pojo.productcategory.Category;
import com.guanyua.eims.dao.CategoryMapper;
import com.guanyua.eims.pojo.productcategory.CategoryDTO;
import com.guanyua.eims.pojo.productcategory.CategoryTreeDTO;
import com.guanyua.eims.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品-分类 服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2020-10-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    /**
     * 获取树结构类目
     */
    @Override
    public List<CategoryTreeDTO> getCategoryTree() {
        List<CategoryDTO> categoryList = categoryMapper.getCategoryList();
        List<CategoryTreeDTO> categoryTreeDTOList = JsonUtil.listTransform(categoryList, CategoryTreeDTO.class);

        //根级类目
        List<CategoryTreeDTO> categoryTree = categoryTreeDTOList.stream().filter(category -> (category.getParentId().equals(0L))).collect(Collectors.toList());

        //递归
        categoryTree.forEach(root -> buildSubs(root, categoryTreeDTOList));

        return categoryTree;
    }

    /**
     * 递归类目
     */
    public void buildSubs(CategoryTreeDTO parent, List<CategoryTreeDTO> subs) {
        List<CategoryTreeDTO> children = subs.stream().filter(sub -> (sub.getParentId().equals(parent.getId()))).collect(Collectors.toList());
        if (children != null && children.size() > 0) {
            parent.setChildren(children);
            children.forEach(child -> buildSubs(child, subs));
        }
    }

}
